﻿using Dispatcher.Core.Message.Models;
using MiniFox;
using MiniFox.Components;
using MiniFox.Platform.Applications.Auth;
using MiniFox.Utility;

namespace Dispatcher.Core.Message
{
    [AutoRegister, SpareComponent(typeof(MessageEngineService))]
    public class MessageEngineService : EngineServiceBase
    {
        public MessageEngineService(SystemPrincipal principal) : base(principal)
        {
        }

        [AutoWired]
        public IMessageProvider Provider { get; set; }

        public virtual async Task<MessageSendResponse> SendAsync(MessageSendRequest sendRequest)
        {
            string messageId = SequenceGUID.NewGUID();

            var sendTime = DateTime.Now;
            var body = await GetBodyContentAsync(sendRequest);
            int count = 0;
            foreach (string receiver in sendRequest.Receiver)
            {
                var user = this.UserProvider.GetUser(receiver);
                var data = new MessageModel
                {
                    MessageId = messageId,
                    GroupName = sendRequest.GroupName,
                    SenderID = this.Principal.GlobalID,
                    SenderName = this.Principal.Name,
                    ReceiverID = user.UserId,
                    ReceiverName = user.DisplayName,
                    Title = sendRequest.Title,
                    Body = body,
                    SendTime = sendTime,
                    Data = sendRequest.Data,
                    TemplateName = sendRequest.TemplateName
                };
                try
                {
                    this.Provider.Sent(data);
                    count++;
                }
                catch (Exception e)
                {
                    this.WriteErrorLog(data.ToJsonString(), e);
                }
            }

            return new MessageSendResponse
            {
                MessageId = messageId,
                SendTime = sendTime
            };
        }

    }
}
